/*
 * ModelLoader.java
 * 
 * Created on 2008-06-30, 18:18:42
 */

package planesimulator.game;

import com.jme.bounding.BoundingBox;
import com.jme.math.FastMath;
import com.jme.math.Quaternion;
import com.jme.math.Vector3f;
import com.jme.scene.Node;
import com.jme.util.export.binary.BinaryImporter;
import com.jmex.model.converters.FormatConverter;
import com.jmex.model.converters.MaxToJme;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.logging.Logger;
import planesimulator.plane.PlaneMath;

/**
 *
 * @author Mateusz 'm4linka' Malinowski (m4linka@gmail.com)
 */
public class ModelLoader {
  
  private final static String MODEL_PATH = 
      "planesimulator/data/model/7.3DS";

  public ModelLoader(Node root_node) {
    FormatConverter file_converter = new MaxToJme();  //the converter
    Node node = null; //Where to dump mesh.
    
    //For loading the raw file
    ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(); 

    // File Path for the model (dump file in toplevel of classpath)
    URL url = Thread.currentThread().getContextClassLoader()
          .getResource(MODEL_PATH); 

    InputStream is=null;
    
    try {
        is=url.openStream();
    } catch(Exception err)  {
        Logger.getLogger(ModelLoader.class.getName()).warning(
            "Could not open Model file: " + err);
    }
    try {

        // Converts the file into a jme usable file
        file_converter.convert(is, bytearrayoutputstream);

        // Used to convert the jme usable file to a TriMesh
        BinaryImporter binaryImporter = new BinaryImporter(); 
        ByteArrayInputStream in = 
            new ByteArrayInputStream(bytearrayoutputstream.toByteArray());

        //importer returns a Loadable, cast to Node
        node = (Node)binaryImporter.load(in); 
    } catch(Exception err)  {
        Logger.getLogger(ModelLoader.class.getName()).warning(
            "Error loading md3 model:"+err);
    }

    // we want pitch the plane about 90 deegree
    final Quaternion pitch90 = new Quaternion();
    pitch90.fromAngleAxis(-FastMath.PI/2, new Vector3f(1,0,0));
    node.setLocalRotation(pitch90);
    
    // we want yaw the plane about 90 deegree
    final Quaternion yaw90 = new Quaternion();
    yaw90.fromAngleAxis(FastMath.PI/2,  new Vector3f(0,1,0));
    
    Quaternion rotation = new Quaternion();
    
    PlaneMath.quatprod(yaw90, pitch90, rotation);
    
    node.setLocalRotation(rotation);

    node.setLocalTranslation(0.0f, 0.0f, 0.0f);
    
//    node.setLocalScale(0.5f);
    
    node.setModelBound(new BoundingBox());
    node.updateModelBound();
    
    //attach node to scene graph
    node.updateRenderState();
    root_node.attachChild(node);
  }
  
}
